// pages/home/index.js
let desc =""
Page({
  /**
   * 页面的初始数据
   */
  data: {
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    haveGetCodeSrc: false,
    codeSrc: '',
    hiddenmodalput:true,  
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  },
  changeData(e){
    desc=e.detail.text
  },
  addUpdateData(){
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('todos').doc('todo-identifiant-aleatoire').set({
      data: {
        description: desc,
      },
      success: function(res) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000,
          success:function(){
            wx.navigateTo({
              url: '../show/index',
            })
          }
        })
      }
    })
  },
  createQr(){
    // this.setData({
    //   codeSrc:"cloud://cloud1-4ggtn84de7e3e302.636c-cloud1-4ggtn84de7e3e302-1354100213/pages_show_index.png",
    //   hiddenmodalput: !this.data.hiddenmodalput  
    // });
    // return


    wx.showLoading({
      title: '正在生成...',
    });
    wx.cloud.callFunction({
      // 云函数名称
      name: 'createQr',
      // 传给云函数的参数
      data: {
        pagePath:'pages/show/index',
      }
    }).then((resp) => {
      console.log(resp) 
      this.setData({
        haveGetCodeSrc: true,
        codeSrc: resp.result,
        hiddenmodalput: !this.data.hiddenmodalput  
      });
      wx.hideLoading();
    }).catch((e) => {
      console.log(e)
      wx.hideLoading();
      const {errCode,errMsg}=e
      if(errMsg.includes('Environment not found')){
        this.setData({
          showTip: true,
          title:"云开发环境未找到",
          content:"如果已经开通云开发，请检查环境ID与 `miniprogram/app.js` 中的 `env` 参数是否一致。"  
        });
        return
      }
      if(errMsg.includes('FunctionName parameter could not be found')){
        this.setData({
          showTip: true,
          title:"请上传云函数",
          content:"在'cloudfunctions/quickstartFunctions'目录右键，选择【上传并部署-云端安装依赖】，等待云函数上传完成后重试。"  
        });
        return
      }
    });
  },
   //取消按钮  
   cancel: function(){  
    this.setData({  
        hiddenmodalput: true  
    });  
},  
//确认  
confirm: function(){   
 wx.cloud.downloadFile({
    fileID:"cloud://cloud1-4ggtn84de7e3e302.636c-cloud1-4ggtn84de7e3e302-1354100213/pages_show_index.png",
    success(res){
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(){
          wx.showToast({
            title: '保存成功',
          })
           
        }
      })
    }
  })


},




  






})